package com.zynn.api.yinian.zuul.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author jerry-liqi
 *
 * 发送邮件服务
 */
@Service
@Slf4j
public class SendMailService {


    private HttpClient httpclient = HttpClients.createDefault();


    /**
     * 发送具体内容
     */
    private final String MSG_TEMPLATE = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"%s;\" }}";

    /**
     * 发送邮件
     * @param content
     */
    public void sendSimpleMail(String title, String content) {
        sendMsg(title+":"+content);
    }

    /**
     * 发送告警通知
     * @param msgValue
     * @return
     */
    private boolean sendMsg(String msgValue) {
        msgValue = msgValue.replace("\"","");
        msgValue = String.format(MSG_TEMPLATE,msgValue);
        HttpPost httppost = new HttpPost("https://oapi.dingtalk.com/robot/send?access_token=358c9a56537639799be703754eb906821ac57bd655b80a224051dd82ab3b8a5a");
        httppost.addHeader("Content-Type", "application/json; charset=utf-8");
        httppost.setEntity(new StringEntity(msgValue, "utf-8"));
        log.info("=sendSMS=>msg=" + msgValue);

        HttpResponse response;
        try {
            response = httpclient.execute(httppost);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                log.info("send SMS ok ,msg=" + result);
            } else {
                log.error("sed SMS error ,status={} ,msg=" + result, response.getStatusLine().getStatusCode());
            }
        } catch (IOException e) {
            log.error("send SMS error:", e);
            return false;
        }
        return true;
    }
}
